package vip

import (
	"errors"
	"net"
	"strings"
)

// Addr represents a VIP with CIDR
type Addr struct {
	IPNet *net.IPNet
	Label string // optional, e.g., eth0:vip
}

func ParseAddr(s string) (*Addr, error) {
	var ipNet *net.IPNet
	var label string

	parts := strings.Split(s, "@")
	ipStr := parts[0]
	if len(parts) > 1 {
		label = parts[1]
	}

	if strings.Contains(ipStr, "/") {
		_, ipNetTmp, err := net.ParseCIDR(ipStr)
		if err != nil {
			return nil, err
		}
		ipNet = ipNetTmp
	} else {
		ip := net.ParseIP(ipStr)
		if ip == nil {
			return nil, errors.New("invalid IP address")
		}
		var mask net.IPMask
		if ip.To4() != nil {
			mask = net.CIDRMask(32, 32)
		} else {
			mask = net.CIDRMask(128, 128)
		}
		ipNet = &net.IPNet{IP: ip, Mask: mask}
	}

	return &Addr{IPNet: ipNet, Label: label}, nil
}
